package cn.crm.service.impl;

import cn.crm.mapper.CrmDepartmentMapper;
import cn.crm.pojo.CrmDepartment;
import cn.crm.pojo.CrmDepartmentExample;
import cn.crm.service.DepartmentService;
import cn.crm.utils.PageUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private CrmDepartmentMapper crmDepartmentMapper;

    //实现分页使用Mybatis的分页插件
    @Override
    public PageUtil findByPage(int page, int size) {
        PageHelper.startPage(page,size);//写在查询所有记录的前边
        //咱们只需要实现查询所有记录
        CrmDepartmentExample example=new CrmDepartmentExample();
//        CrmDepartmentExample.Criteria criteria = example.createCriteria();
//        criteria.andDepidEqualTo(77);
        //查询所有记录  limit (page-1)*size,size
        List<CrmDepartment> data = crmDepartmentMapper.selectByExample(example);

        PageUtil pageUtil=new PageUtil();
        pageUtil.setDatas(data);//当前页的数据

        pageUtil.setCurrentPage(page);//设置当前页

        PageInfo<CrmDepartment> info = new PageInfo<>(data);
        long total = info.getTotal();//得到总记录数 表中一共有多少条记录

        long totalpage= total/size;  //计算总页数
        if(total%size!=0)
            totalpage++;

        pageUtil.setTotalPage(totalpage);
        return pageUtil;
    }

    //根据部门id查询部门信息
    @Override
    public CrmDepartment findDepartInfo(String depId) {

        CrmDepartment crmDepartment = crmDepartmentMapper.selectByPrimaryKey(depId);
        return crmDepartment;
    }

    //修改部门信息
    @Override
    public void updateDepartmentInfo(CrmDepartment crmDepartment) {

        crmDepartmentMapper.updateByPrimaryKey(crmDepartment);
    }

    //添加部门
    @Override
    public void addDepart(CrmDepartment crmDepartment) {
        //页面上没有的数据需要补全
        //生成id值
        String depId=UUID.randomUUID().toString();
        crmDepartment.setDepid(depId);

        crmDepartmentMapper.insert(crmDepartment);
    }

    //查询所有部门
    @Override
    public List<CrmDepartment> findAllDepartments() {
        CrmDepartmentExample example=new CrmDepartmentExample();
        //CrmDepartmentExample.Criteria criteria = example.createCriteria();
        List<CrmDepartment> crmDepartments = crmDepartmentMapper.selectByExample(example);

        return crmDepartments;
    }
}
